import { request } from "../../request/index.js"
Page({
  data: {
    goodsDetail: {},
    isCollect: false
  },
  goodsInfo: {},
  urls: [],
  onShow() {
    let pages = getCurrentPages();
    let currentPage = pages[pages.length - 1];
    const { options } = currentPage
    const { goods_id } = options
    this.getgoodsDetail(goods_id)

  },
  async getgoodsDetail(goods_id) {
    const res = await request({
      url: "goods/detail", data: { goods_id }
    })
    this.goodsInfo = res.data.message

    let collect = wx.getStorageSync('collect') || []
    let isCollect = collect.some(v =>
      v.goods_id == goods_id
    )
    console.log(isCollect);
    this.urls = res.data.message.pics.map(v => v.pics_mid)
    this.setData({
      isCollect,
      goodsDetail: {
        goods_name: res.data.message.goods_name,
        goods_price: res.data.message.goods_price,
        pics: res.data.message.pics,
        goods_introduce: res.data.message.goods_introduce.replace(/\.webp/g, '.jpg')
      },
    })
  },
  handleimgTap(e) {
    wx.previewImage({
      current: e.currentTarget.dataset.url, // 当前显示图片的http链接
      urls: this.urls // 需要预览的图片http链接列表
    })
  },
  handleAddCart() {
    let cart = wx.getStorageSync("cart") || []
    let index = cart.findIndex(v => v.goods_id === this.goodsInfo.goods_id)
    if (index === -1) {
      this.goodsInfo.num = 1
      this.goodsInfo.check = true
      cart.push(this.goodsInfo)
    } else {
      cart[index].num++
    }
    wx.setStorageSync('cart', cart);
  },
  handleCollect() {
    let { isCollect } = this.data
    isCollect = !isCollect
    let collect = wx.getStorageSync("collect") || []
    let index = collect.findIndex(v => v.goods_id = this.goodsInfo.goods_id)
    // if (index !== -1) {
    //   collect.splice(index, 1)
    // } else {
    //   collect.push(this.goodsInfo)
    // }


    if (isCollect) {
      collect.push(this.goodsInfo)
      isCollect = true
    } else {
      collect.splice(index, 1)
      isCollect = false
    }

    wx.setStorageSync('collect', collect)
    this.setData({
      isCollect
    })
  }
})